package com.ff.exerpro.advice;

import com.ff.exerpro.common.R;
import com.ff.exerpro.exception.BussException;
import com.ff.exerpro.exception.BussExceptionEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {
    // 全局兜底异常返回最基本错误
    @ExceptionHandler(Throwable.class)
    public R exception(Throwable e) {
        e.printStackTrace();
        return R.error();
    }

    // 数据验证错误
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R methodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();

        BindingResult bindingResult = e.getBindingResult();

        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String, String> map = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return R.error(BussExceptionEnum.INVALID_PARAM.getCode(), BussExceptionEnum.INVALID_PARAM.getMsg(), map);
    }

    // 业务错误
    @ExceptionHandler(BussException.class)
    public R bussException(BussException e) {
        e.printStackTrace();
        return R.error(e.getCode(), e.getMessage(), e.getData());
    }
}
